package com.a1w0n.standard;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;

import java.io.*;

public class ScreenShot {
    final static String TAG = "ScreenShot";
    /**
     * @throws InterruptedException
     */
    public static void shot() throws InterruptedException {
        try {
            //分辨率大小，后续可以通过代码来获取到当前的分辨率  
            int xResolution = 320;
            int yResolution = 480;
            //执行adb命令，把framebuffer中内容保存到fb1文件中  
//             Runtime.getRuntime().exec("adb pull /dev/graphics/fb0 C:/fb1");
            //等待几秒保证framebuffer中的数据都被保存下来，如果没有保存完成进行读取操作会有IO异常
            Thread.sleep(15000);
            long time1, time2;
            time1 = System.currentTimeMillis();
            //读取文件中的数据
            InputStream in = (InputStream) new FileInputStream("/dev/graphics/fb0");
//            DataInput frameBuffer = new DataInputStream(in);
            BufferedInputStream bis = new BufferedInputStream(in);
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            FileOutputStream fout = new FileOutputStream("/sdcard/sc00.png");
            time2 = System.currentTimeMillis();
            System.out.println("\n\n1 cmd time:" + (time2 - time1));
            byte[] buffer = new byte[1];
            while (bis.read(buffer) > 0) {
                fout.write(buffer);
                bout.write(buffer);
            }
            System.out.println(new String(bout.toByteArray(), "utf-8"));
            fout.flush();
            fout.close();
            time1 = System.currentTimeMillis();
            System.out.println("2 read buffer time:" + (time1 - time2));
//            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
//            DataInputStream dis = new DataInputStream(bin);
            Bitmap bitmap = decodeFrameToBitmap(bout.toByteArray());
//            Bitmap bitmap = BitmapFactory.decodeStream(dis);
            time2 = System.currentTimeMillis();
            System.out.println("3 buffer2img time:" + (time2 - time1));
            saveBitmap("sc01.png", bitmap);

//            BufferedImage screenImage = new BufferedImage(
//                    xResolution, yResolution, BufferedImage.TYPE_INT_ARGB);
//            int[] oneLine = new int[xResolution];
//            for (int y = 0; y < yResolution; y++) {
//                //从frameBuffer中计算出rgb值
//                convertToRgba32(frameBuffer, oneLine);
//                //把rgb值设置到image对象中
//                screenImage.setRGB(0, y, xResolution, 1, oneLine, 0, xResolution);
//            }
//            Closeables.closeQuietly(in);
//
//            ByteArrayOutputStream rawPngStream = new ByteArrayOutputStream();
//            try {
//                if (!ImageIO.write(screenImage, "png", rawPngStream)) {
//                    throw new RuntimeException(
//                            "This Java environment does not support converting to PNG.");
//                }
//            } catch (IOException exception) {
//                // This should never happen because rawPngStream is an in-memory stream.
//                System.out.println("IOException=" + exception);
//            }
//            byte[] rawPngBytes = rawPngStream.toByteArray();
//            String base64Png = new Base64Encoder().encode(rawPngBytes);
//
//            File screenshot = OutputType.FILE.convertFromBase64Png(base64Png);
//            System.out.println("screenshot==" + screenshot.toString());
//            screenshot.renameTo(new File("C:\\screenshottemp.png"));

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e);
        }
    }

    //这种方法状态栏是空白，显示不了状态栏的信息

    public static int convertByteToInt(byte data){

        int heightBit = (int) ((data>>4) & 0x0F);
        int lowBit = (int) (0x0F & data);

        return heightBit * 16 + lowBit;
    }

    public static int[] convertByteToColor(byte[] data){
        int size = data.length;
        if (size == 0){
            return null;
        }

        int arg = 0;
        if (size % 3 != 0){
            arg = 1;
        }

        int []color = new int[size / 3 + arg];
        int red, green, blue;

        if (arg == 0){
            for(int i = 0; i < color.length; ++i){
                red = convertByteToInt(data[i * 3]);
                green = convertByteToInt(data[i * 3 + 1]);
                blue = convertByteToInt(data[i * 3 + 2]);

                color[i] = (red << 16) | (green << 8) | blue | 0xFF000000;
            }
        }else{
            for(int i = 0; i < color.length - 1; ++i){
                red = convertByteToInt(data[i * 3]);
                green = convertByteToInt(data[i * 3 + 1]);
                blue = convertByteToInt(data[i * 3 + 2]);
                color[i] = (red << 16) | (green << 8) | blue | 0xFF000000;
            }

            color[color.length - 1] = 0xFF000000;
        }

        return color;
    }
    static Bitmap decodeFrameToBitmap(byte[] frame)
    {
        int []colors = convertByteToColor(frame);
        if (colors == null){
            return null;
        }
        Bitmap bmp = Bitmap.createBitmap(colors, 0, 1280, 1280, 720,Bitmap.Config.ARGB_8888);
        return bmp;
    }
    Bitmap Bytes2Bimap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }
    public static void convertToRgba32(DataInput frameBuffer, int[] into) {
        try {
            for (int x = 0; x < into.length; x++) {
                try {
                    int rgb = frameBuffer.readShort() & 0xffff;
                    int red = rgb >> 11;
                    red = (red << 3) | (red >> 2);
                    int green = (rgb >> 5) & 63;
                    green = (green << 2) | (green >> 4);
                    int blue = rgb & 31;
                    blue = (blue << 3) | (blue >> 2);
                    into[x] = 0xff000000 | (red << 16) | (green << 8) | blue;
                } catch (EOFException e) {
                    System.out.println("EOFException=" + e);
                }
            }
        } catch (IOException exception) {
            System.out.println("convertToRgba32Exception=" + exception);
        }
    }

    static void saveBitmap(String fileName, Bitmap bm) {
        Log.d(TAG, "保存图片");
        if(bm == null){
            Log.d(TAG, "Bitmap is null");
            return;
        }
        File f = new File("/sdcard/", fileName);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            Log.i(TAG, "已经保存");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}  